package patrol.mobile.com.mobilepatrol.activity.track;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.realm.Realm;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.bean.PatrolInfoBean;
import patrol.mobile.com.mobilepatrol.bean.Route;
import patrol.mobile.com.mobilepatrol.manager.CarManager;
import patrol.mobile.com.mobilepatrol.manager.RouteManager;
import patrol.mobile.com.mobilepatrol.manager.TrackManager;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.DateUtil;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.widget.datepicker.CustomDatePicker;

import static patrol.mobile.com.mobilepatrol.R.id.tv;

/**
 * Created by apple on 17/11/6.
 */

public class AddTrackActivity extends BaseActivity {
    @BindView(R.id.item1)
    RelativeLayout rl1;

    @BindView(R.id.item2)
    RelativeLayout rl2;

    @BindView(R.id.item3)
    RelativeLayout rl3;

    @BindView(R.id.item4)
    RelativeLayout rl4;

    @BindView(R.id.item5)
    RelativeLayout rl5;

    @BindView(R.id.item6)
    RelativeLayout rl6;

    @BindView(R.id.item7)
    RelativeLayout rl7;

    @BindView(R.id.item8)
    RelativeLayout rl8;

    @BindView(R.id.sure)
    Button bt_sure;

    private TextView tv_date;
    private TextView tv_weather;
    private TextView tv_roader;
    private EditText et_skm;
    private EditText et_smeter;

    private EditText et_eKm;
    private EditText et_eMeter;
    /** popup窗口里的ListView */
    private ListView mWeatherLv;
    /** popup窗口 */
    private PopupWindow weatherPopup;

    /** 模拟的假数据 */
    private List<String> weatherData = new ArrayList<>();
    private List<String> patrolTypeData = new ArrayList<>();
//    private List<String> roadCarData = new ArrayList<>();
//    private List<String> roadLineData = new ArrayList<>();

    private TextView tv_patrolType;
    private TextView tv_roadCar;
    private TextView tv_roadLine;
    private PopupWindow mPopup;
    private boolean isAlter;
    private String mID;

    private String init_date;
    private String init_patrolType;
    private String init_weather;
    private String init_roader;
    private String init_car;
    private String init_line;
    private int init_sKM;
    private int init_sMeter;
    private int init_ekm;
    private int init_eMeter;
    private Route mRoadLine;
    private CustomDatePicker customDatePicker;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_track_add;
    }

    @Override
    public void setListener() {
        bt_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAlter){
                    alter();
                }else{
                    insert();
                }

            }


        });
        //巡查类型
        rl2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initSelectPopup(patrolTypeData,tv_patrolType);
                if (mPopup != null && !mPopup.isShowing()) {
                    mPopup.showAsDropDown(tv_patrolType, 0, 10);
                }
            }
        });
        rl3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initSelectPopup(weatherData,tv_weather);
                if (mPopup != null && !mPopup.isShowing()) {
                    mPopup.showAsDropDown(tv_weather, 0, 10);
                }

            }
        });
        rl5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddTrackActivity.this,CarListActivity.class);
                startActivityForResult(intent,0);
                CommonUtil.openNewActivityAnim(AddTrackActivity.this,false);

            }
        });
        rl6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddTrackActivity.this,RouteListActivity.class);
                startActivityForResult(intent,0);
                CommonUtil.openNewActivityAnim(AddTrackActivity.this,false);

            }
        });
    }

    private void alter() {
        final String roadDate = tv_date.getText().toString().trim();
        final String patrolType = tv_patrolType.getText().toString().trim();
        final String weather = tv_weather.getText().toString().trim();
        final String roader = tv_roader.getText().toString().trim();
        final String roadCar = tv_roadCar.getText().toString().trim();
        final String roadLine = tv_roadLine.getText().toString().trim();
        final String startKM = et_skm.getText().toString().trim();
        final String startMeter = et_smeter.getText().toString().trim();
        final String endKM = et_eKm.getText().toString().trim();
        final String endMeter = CommonUtil.getText(et_eMeter);
        PatrolApp.realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                List<PatrolInfoBean> mlist = realm.where(PatrolInfoBean.class).equalTo("ID",mID).findAll();
                PatrolInfoBean p = mlist.get(0);
                p.ID = mID;
                p.startPot = "K";
                p.endPot="K";
                p.orgID = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).bmcode;
                p.orgName = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).bmname;
                p.patrolDetailNum = TrackManager.getAllDetailCounts(mID);
                p.roadLineID = mRoadLine.manageID;
                p.roaderID = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).ryid;
                p.updatetime = System.currentTimeMillis();
                p.roadDate = roadDate;
                p.patrolType = patrolType;
                p.weather = weather;
                p.roader = roader;
                p.roadCar = roadCar;
                p.roadLine = roadLine;
                p.startPotKm = Integer.valueOf(startKM);
                p.startPotMeter = Integer.valueOf(startMeter);
                p.endPotKm = Integer.valueOf(endKM);
                p.endPotMeter = Integer.valueOf(endMeter);
                p.status = 0;
            }
        });

        showToast("修改成功");
        Intent intent = new Intent(AddTrackActivity.this,TrackDetailActivity.class);
        intent.putExtra("ID",mID);
        intent.putExtra("alter",false);
        startActivity(intent);
        CommonUtil.openNewActivityAnim(AddTrackActivity.this,true);
    }

    private void insert() {
        String roadDate = tv_date.getText().toString().trim();
        String patrolType = tv_patrolType.getText().toString().trim();
        String weather = tv_weather.getText().toString().trim();
        String roader = tv_roader.getText().toString().trim();
        String roadCar = tv_roadCar.getText().toString().trim();
        String roadLine = tv_roadLine.getText().toString().trim();
        String skm = et_skm.getText().toString().trim();
        String smeter = et_smeter.getText().toString().trim();
        String ekm = et_eKm.getText().toString().trim();
        String emeter = CommonUtil.getText(et_eMeter);
        PatrolInfoBean p = new PatrolInfoBean();
        p.ID = CommonUtil.getUUID();
        p.startPot = "K";
        p.endPot = "K";
        p.orgID = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).bmcode;
        p.orgName = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).bmname;
        p.patrolDetailNum = 0;
        p.roadDate = roadDate;
        p.patrolType = patrolType;
        p.weather = weather;
        p.roader = roader;
        p.roaderID = UserManager.getUser((String) SPUtils.get(Constants.current_id,"")).ryid;
        p.roadCar = roadCar;
        p.roadLine = roadLine;
        p.roadLineID = mRoadLine.manageID;
        p.startPotMeter = Integer.valueOf(smeter);
        p.startPotKm = Integer.valueOf(skm);
        p.endPotMeter = Integer.valueOf(emeter);
        p.endPotKm = Integer.valueOf(ekm);
        p.updatetime = System.currentTimeMillis();
        p.status = 0;
        TrackManager.insertT(p);

        showToast("添加成功");
        Intent intent = new Intent(AddTrackActivity.this,TrackDetailActivity.class);
        intent.putExtra("ID",p.ID);
        intent.putExtra("alter",false);
        startActivity(intent);
        CommonUtil.openNewActivityAnim(AddTrackActivity.this,true);
    }


    private void iniData() {
        Resources resources = getResources();
        String[] patrolTypes = resources.getStringArray(R.array.patrolType);
        String[] weathers = resources.getStringArray(R.array.weather);
            for (int i = 0; i < weathers.length; i++) {
                weatherData.add(weathers[i]);
            }
            for (int i = 0; i < patrolTypes.length; i++) {
                patrolTypeData.add(patrolTypes[i]);
            }
        isAlter = getIntent().getBooleanExtra("alter",false);
        if (isAlter){
            mID = getIntent().getStringExtra("ID");
            PatrolInfoBean patrol = TrackManager.getPatrol(mID);
            init_patrolType = patrol.patrolType;
            init_weather = patrol.weather;
            init_date = patrol.roadDate;
            init_roader = patrol.roader;
            init_car = patrol.roadCar;
            mRoadLine = RouteManager.getRoute(patrol.roadLineID);
            init_line = patrol.roadLine;
            init_sKM= patrol.startPotKm;
            init_sMeter = patrol.startPotMeter;
            init_ekm = patrol.endPotKm;
            init_eMeter = patrol.endPotMeter;

        }else{
            init_patrolType = patrolTypeData.get(0);
            init_weather = weatherData.get(0);
            init_date = DateUtil.getCurrentDate(Constants.formatdate);
            init_roader = UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).ryname;
            init_car = CarManager.getFirstCar().carNumber;
            mRoadLine = RouteManager.getFirstRoute();
            init_line = mRoadLine.routeName;
            init_sKM= mRoadLine.startPotKm;
            init_sMeter = mRoadLine.startPotMeter;
            init_ekm = mRoadLine.endPotKm;
            init_eMeter = mRoadLine.endPotMeter;
        }
    }

    @Override
    public void initView() {
        super.initView();
        iniData();
        TextView tv1 = rl1.findViewById(tv);
        tv1.setText("检查日期:");
        tv_date = rl1.findViewById(R.id.tv1);
        tv_date.setText(init_date);

        TextView tv2 = rl2.findViewById(tv);
        tv2.setText("巡查类型");
        tv_patrolType = rl2.findViewById(R.id.tv1);
        tv_patrolType.setText(init_patrolType);

        TextView tv3 = rl3.findViewById(tv);
        tv3.setText("今日天气：");
        tv_weather = rl3.findViewById(R.id.tv1);
        tv_weather.setText(init_weather);

        TextView tv4 = rl4.findViewById(tv);
        tv4.setText("巡查人员：");
        tv_roader = rl4.findViewById(R.id.tv1);
        tv_roader.setText(init_roader);

        TextView tv5 = rl5.findViewById(tv);
        tv5.setText("巡查车辆：");
        tv_roadCar = rl5.findViewById(R.id.tv1);
        tv_roadCar.setText(init_car);

        TextView tv6 = rl6.findViewById(tv);
        tv6.setText("巡查路线：");
        tv_roadLine = rl6.findViewById(R.id.tv1);
        tv_roadLine.setText(init_line);


        TextView tv7 = rl7.findViewById(R.id.tv1);
        tv7.setText("起始桩号：");
        et_skm = rl7.findViewById(R.id.et1);
        et_smeter = rl7.findViewById(R.id.et2);
        et_skm.setText(init_sKM+"");
        et_smeter.setText(String.valueOf(init_sMeter));

        TextView tv8 = rl8.findViewById(R.id.tv1);
        tv8.setText("终点桩号：");
        et_eKm = rl8.findViewById(R.id.et1);
        et_eMeter = rl8.findViewById(R.id.et2);
        et_eKm.setText(init_ekm+"");
        et_eMeter.setText(String.valueOf(init_eMeter));

    }

    /**
     * 初始化popup窗口
     */
    private void initSelectPopup(final List<String> mData, final TextView mTv) {
        ListView mLv = new ListView(this);
        // 设置适配器
        ArrayAdapter mAdapter = new ArrayAdapter<String>(this, R.layout.popup_text_item, mData);
        mLv.setAdapter(mAdapter);

        // 设置ListView点击事件监听
        mLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 在这里获取item数据
                String value = mData.get(position);
                // 把选择的数据展示对应的TextView上
                mTv.setText(value);
                mPopup.dismiss();
            }
        });
        mPopup = new PopupWindow(mLv, mTv.getWidth(), ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 取得popup窗口的背景图片
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg1);
        mPopup.setBackgroundDrawable(drawable);
        mPopup.setFocusable(true);
        mPopup.setOutsideTouchable(true);
        mPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 关闭popup窗口
                mPopup.dismiss();
            }
        });
    }
    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(AddTrackActivity.this,true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("巡道");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 1:
                String car = data.getStringExtra("name");
                tv_roadCar.setText(car);
                break;
            case 2:
                String id = data.getStringExtra("id");
                mRoadLine = RouteManager.getRoute(id);
                tv_roadLine.setText(mRoadLine.routeName);
                et_skm.setText(mRoadLine.startPotKm+"");
                et_smeter.setText(mRoadLine.startPotMeter+"");
                et_eKm.setText(mRoadLine.endPotKm+"");
                et_eMeter.setText(mRoadLine.endPotMeter+"");
                break;
        }
    }
}
